package by.bsu.scs.presentation.form;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

import by.bsu.scs.db.dao.UserHome;
import by.bsu.scs.model.User;
import by.bsu.scs.security.MD5Encoder;
import by.bsu.scs.util.filter.AuthorizationFilter;

/**
 * @author Alexey Hursevich
 * @version 1.0
 * 
 * Login form bean.
 */
public class LoginForm extends ActionForm {
	private static final long serialVersionUID = 1L;
	
	private String userName;
	private String password;
	private String localization;
	
	private boolean rememberMe;
	
	/**
	 * Validate authorization procedure - checks user existence in DB and
	 * verifies the correspondence of password for the user.
	 * 
	 * @param mapping
	 * @param request
	 * 
	 * @return errors
	 */
	public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
		ActionErrors errors = new ActionErrors();
		
		if( ((String)request.getAttribute(AuthorizationFilter.IS_AUTORIZED)) == null ||  
		   !((String)request.getAttribute(AuthorizationFilter.IS_AUTORIZED)).equalsIgnoreCase("true")) 
		{
			User user = new User();
			UserHome userHome = new UserHome();
			
			user.setEmail(userName);
			if(userHome.findByExample(user).size() == 0) {
				errors.add("userName", new ActionMessage("error.userName.invalid"));
			}
			
			user.setPassword(MD5Encoder.getHash(password));
			if(userHome.findByExample(user).size() == 0) {
				errors.add("password", new ActionMessage("error.password.invalid"));
			}
		}
		return errors;
	}
	
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public boolean isRememberMe() {
		return rememberMe;
	}
	public void setRememberMe(boolean rememberMe) {
		this.rememberMe = rememberMe;
	}
	public String getLocalization() {
		return localization;
	}
	public void setLocalization(String localization) {
		this.localization = localization;
	}
}
